# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         http_session_context.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 17:32
# -------------------------------------------------------------------------------

from apps.HttpAutoTestService.core import utils


class HttpSessionContext(object):
    """会话上下文，用在存储运行时变量"""

    def __init__(self, environment_variables=None, project_variables=None, testsuite_variables=None):
        self.session_variables_mapping = {}
        self.output_variables_mapping = {}
        self.update_session_variables(environment_variables or {})
        self.update_session_variables(project_variables or {})
        self.update_session_variables(testsuite_variables or {})

    def update_session_variables(self, variables_mapping):
        """
        更新HttpSessionContext实例的变量
        Args:
            variables_mapping: 变量参数

        Returns:

        """
        variables_mapping = utils.ensure_mapping_format(variables_mapping)
        if variables_mapping:
            self.session_variables_mapping.update(variables_mapping)

    def update_output_variables(self, variables_mapping):
        variables_mapping = utils.ensure_mapping_format(variables_mapping)
        if variables_mapping:
            self.output_variables_mapping.update(variables_mapping)

    def get_output_variable(self, name):
        return self.output_variables_mapping.get(name, None)

    def get_session_variable(self, name):
        return self.session_variables_mapping.get(name, None)

    def get_variable(self, name):
        if name in list(self.output_variables_mapping.keys()):
            return self.get_output_variable(name)
        elif name in list(self.session_variables_mapping.keys()):
            return self.get_session_variable(name)
        else:
            return None

    def get_session_variable_keys(self):
        return list(self.session_variables_mapping.keys())

    def get_output_variable_keys(self):
        return list(self.output_variables_mapping.keys())
